package com.jydd.liaomingframe.login;

import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jydd.liaomingframe.main.MainActivity;
import com.jydd.liaomingframe.R;
import com.jydd.liaomingframe.common.BaseRepositon;
import com.jydd.liaomingframe.common.BaseResult;
import com.lm.liaoming.base.custom.CustomBaseActivity;
import com.lm.liaoming.constant.ConstantValues;
import com.lm.liaoming.http.RetrofitManger;
import com.lm.liaoming.manager.DialogManager;
import com.lm.liaoming.tool.Utils;
import com.tumblr.remember.Remember;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.GONE;

/**
 * author: 韦敏敏
 * date: 2019/11/17 0017
 */
public class LoginActivity extends CustomBaseActivity {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.phonenumber)
    EditText phoneNumber;
    @BindView(R.id.password)
    EditText passWord;
    @BindView(R.id.toolbar_title)
    TextView tvToolbarTitle;
    private String account, password;
    private BaseRepositon mBaseRepositon;
    @Override
    public void initVariables() {
        mBaseRepositon = RetrofitManger.initRetrofitJava(this).create(BaseRepositon.class);
    }
    @Override
    public void initViews() {
        ButterKnife.bind(this);
        back.setVisibility(GONE);
        tvToolbarTitle.setText("登录");
        tvToolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.black3));
        tvToolbarTitle.setTextSize(18);
    }
    @Override
    public int setLayoutId() {
        return R.layout.activity_login;
    }
    private boolean verifyLoginInfo(){
        account = phoneNumber.getText().toString().trim();
        password = passWord.getText().toString().trim();
        if(TextUtils.isEmpty(account)){
            showToast("请输入账号");
            return true;
        }
        if(TextUtils.isEmpty(password)){
            showToast("请输入密码");
            return true;
        }
        return false;
    }
    @OnClick(R.id.btn_login)
    public void onLoginClick(){
        if (verifyLoginInfo())
            return;
        LoginParam param = new LoginParam();
        param.setAccount(account);
        param.setPassword(password);
        // 判断是否有设备正在登陆此账号
        huti(param);
    }
    private void huti(LoginParam param) {
        DialogManager.showErrorToath(this, "登录中");
        mBaseRepositon.loginOut(param.getAccount(), "xttz").enqueue(new Callback<Object>() {

            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                String currentThreadName = Thread.currentThread().getName();
                Utils.i("huti, onResponse ->  线程名称：  " + currentThreadName);
                Future future = Utils.executorService.submit(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        String currentThreadName = Thread.currentThread().getName();
                        Utils.i("huti1, onResponse ->  线程名称1：  " + currentThreadName);
                        // 执行登录
                        login(param.getAccount(), param.getPassword());
                        return "我真的执行完了";
                    }
                });
                try {
                    String result = (String) future.get();
                    Utils.i("loging-huti, threadResult : " + result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<Object> call, Throwable t) {

            }
        });
    }

    private void login(String account, String password) {
        HashMap<String, String> userMap = new HashMap<>();
        userMap.put("account", account);
        userMap.put("password", password);
        userMap.put("phoneNum", Build.MODEL);
        userMap.put("appVersion", Utils.getVersionName(this).getVersionName());
        userMap.put("androidVersion", android.os.Build.VERSION.RELEASE);
        mBaseRepositon.login(userMap).enqueue(new Callback<BaseResult>() {
            @Override
            public void onResponse(Call<BaseResult> call, Response<BaseResult> response) {
                Gson gson = new Gson();
                String threadName = Thread.currentThread().getName();
                Utils.i("login, response - >  threadName : " + threadName);
                // Cookie
                Headers headers = response.headers();
                HttpUrl httpUrl = call.request().url();
                List<Cookie> cookieList = Cookie.parseAll(httpUrl, headers);
                Cookie cookie = cookieList.get(0);
                String cookieKey = cookie.name();
                String cookieValue = cookie.value();
                // 对响应数据的处理相关
                BaseResult baseResult = response.body();
                Integer integer = Integer.valueOf(response.code());
                if(baseResult == null){
                    showToast("System Error!");
                    return;
                }
                if(integer != null && integer.intValue() == 200){
                    showToast("登录成功!");
                    Object object = baseResult.getData();
                    String data = gson.toJson(object);
                    LoginResultBean loginResultBean = gson.fromJson(data, LoginResultBean.class);
                    if(loginResultBean != null){
                        Remember.putString(ConstantValues.TOKEN_VALUE, loginResultBean.getId());
                    }
                    /*cookie*/
                    Remember.putString(ConstantValues.COOKIE_KEY, cookieKey);
                    Remember.putString(ConstantValues.COOKIE_VALUE, cookieValue);
                    /*loginState*/
                    Remember.putBoolean(ConstantValues.LOGIN_STATUS, true);
                    Remember.putBoolean(ConstantValues.LOADING, true);
                    // 跳转
                    Intent intent = new Intent();
                    intent.setClass(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    showToast(baseResult.getMsg() == null ? "System Error" : baseResult.getMsg());
                }
                DialogManager.dimissDialog();
            }
            @Override
            public void onFailure(Call<BaseResult> call, Throwable t) {
                Utils.i("login, onFailure - > " + t.getMessage());
            }
        });

    }
}
